//
//  CatchCrashException.swift
//  XWHAOfflineFitting
//
//  Created by edy on 2024/7/23.
//

import Foundation

//void InstallUncaughtExceptionHandler(void) {
//    NSSetUncaughtExceptionHandler( &handleUncaughtException );
//}
//
//void handleUncaughtException(NSException *exception) {
//    NSString * crashInfo = [NSString stringWithFormat:@"yyyy Exception name：%@\nException reason：%@\nException stack：%@",[exception name], [exception reason], [exception callStackSymbols]];
//    NSLog(@"%@", crashInfo);
//}

private var previoursHandler: NSUncaughtExceptionHandler? = nil

public func catchUncaughtNSException(completion: NSUncaughtExceptionHandler? = nil) {
    previoursHandler = completion
    
    if previoursHandler == nil {
        previoursHandler = NSGetUncaughtExceptionHandler()
    }
    
    NSSetUncaughtExceptionHandler { e in
        // 写log文件保存crash信息等操作
        // 调用先前的handler
        previoursHandler?(e)
        
//        let eName = e.name
//        let eReason = e.reason ?? ""
//        let eCallStackSymbols = e.callStackSymbols
//        
//        let eInfo = "\(eName), \(eReason)\n callStackSymbols = \n\(eCallStackSymbols)"
//        print("App Crash Info: \n\(eInfo)")
        
        // 杀掉程序，这样可以防止同时抛出的SIGABRT被Signal异常捕获
//        kill(getpid(), SIGKILL)
    }
}
